package handler

import (
	"class/api/request"
	"class/glodal"
	"class/model"
	"class/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
)

func CourseAdd(context *gin.Context) {
	var req request.Course
	if err := context.ShouldBind(&req); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "参数错误",
		})
		return
	}
	course := model.Course{
		UserId: req.UserId,
		Title:  req.Title,
		Intro:  req.Intro,
		Price:  req.Price,
		Status: req.Status,
		Reason: req.Reason,
	}
	glodal.DB.Create(&course)
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "发布成功",
		"data":    course.ID,
	})
}

func CourseList(context *gin.Context) {
	var req request.CourseList
	if err := context.ShouldBind(&req); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "参数错误",
		})
		return
	}
	page := req.Page
	if page <= 0 {
		page = 1
	}
	pageSize := req.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize
	var courses []model.Course
	glodal.DB.Where("user_id = ?", req.UserId).Offset(offset).Limit(pageSize).Find(&courses)
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "查询成功",
		"data":    courses,
	})
}

func ReviewList(context *gin.Context) {
	var req request.Review
	if err := context.ShouldBind(&req); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "参数错误",
		})
		return
	}
	var course []model.Course
	glodal.DB.Where("status = ?", req.Status).Find(&course)
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "查看成功",
		"data":    course,
	})
}

func Review(context *gin.Context) {
	var req request.Review
	if err := context.ShouldBind(&req); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "参数错误",
		})
		return
	}
	var course []model.Course
	glodal.DB.Model(&course).Where("status = ?", req.Status).Update("status", 2)
	rabbitmq := pkg.NewRabbitMQSimple("course")
	rabbitmq.PublishSimple("审核通过")

	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "审核通过",
	})
}

func ReviewAdd(context *gin.Context) {
	var req request.ReviewAdd
	if err := context.ShouldBind(&req); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "参数错误",
		})
		return
	}
	tx := glodal.DB.Begin()
	var course model.Course
	tx.Where("course_id = ?", req.CourseId).First(&course)
	review := model.Review{
		UserId: course.UserId,
		Status: course.Status,
	}
	tx.Create(&review)
	tx.Commit()
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "记录成功",
		"data":    review.ID,
	})
}
